import { getToken, setToken, removeToken } from '@/utils/cookie'
import { loginIn } from '@/api/user'

const state = {
  userInfo: {},
  userPermission: [],
  userToken: getToken(),
  isLogin: false,
}

const mutations = {
  SET_USER_INFO: (state, userData) => {
    sessionStorage.setItem('userInfo', JSON.stringify(userData))
    state.userInfo = userData
  },
  SET_USER_PERMISSION: (state, permission) => {
    sessionStorage.setItem('userPermission', JSON.stringify(permission))
    state.userPermission = permission
  },
  SET_USER_TOKEN: (state, tokenData) => {
    state.userToken = tokenData
  },
  SET_LOGIN_STATUS: (state, status) => {
    state.isLogin = status
    console.log(state.isLogin)
  },
}

const getters = {
  userInfo: state => {
    return state.userInfo
  },
  userPermission: state => {
    return state.userPermission
  },
  userToken: state => {
    return state.userToken
  },
  isLogin: state => {
    return state.isLogin
  }
}

const actions = {
  // 登录
  async userLogin({ commit }, userData) {
    const { access_token } = await loginIn({
      username: userData.username.trim(),
      password: window.btoa(userData.password)
    })
    setToken(access_token)
    commit('SET_USER_TOKEN', access_token)
    commit('SET_LOGIN_STATUS', true)
  },
  // 删除 token, 清除用户数据
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_USER_TOKEN', '')
      commit('SET_LOGIN_STATUS', false)
      removeToken()
      sessionStorage.clear()
      resolve()
    })
  },
}

export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations
}